﻿using System;
using System.IO;
using AjaxControlToolkit;
using Foothill.Common;
using Foothill.Common.Logging;
using Foothill.IoC;
using Foothill.Model;
using Foothill.Service.Security;
using Foothill.Service.UploadPhoto;
using Foothill.Service.UserAccount;
using Foothill.Service.Validation;
using Foothill.Web.UserProfile.App_LocalResources;

namespace Foothill.Web.UserProfile
{
    public partial class EditProfile : System.Web.UI.Page
    {
        private IUserAccountService _userAccountService;
        private ISecurityService _securityService;
        private IUploadFileManager _uploadFileManager;
        
        protected void Page_Load(object sender, EventArgs e)
        {
            _securityService = IocContainer.GetInstance<ISecurityService>();
            if (!_securityService.IsCurrentUserAuthenticated())
            {
                Response.Redirect("~/Login/Login.aspx");
            }
            else
            {
                if (!IsPostBack)
                {
                    PopulatePage();
                }
            }
        }

        private void PopulatePage()
        {
            CurrentLoginUser currentLoginUser = _securityService.GetLoginUserDetails();

            if (currentLoginUser != null)
            {
                lblUserName.Text = currentLoginUser.UserAccountInfo.Username;
                txtPhone.Text = currentLoginUser.UserAccountInfo.ContactPhone;
                txtContactName.Text = currentLoginUser.UserAccountInfo.ContactName;
                tbxIntro.Text = currentLoginUser.UserAccountInfo.Intro;

                DisplayProfilePhoto(currentLoginUser);
                DisplayLogo(currentLoginUser);
            }
        }

        private void DisplayLogo(CurrentLoginUser currentLoginUser)
        {
            if (currentLoginUser == null)
            {
                return;
            }

            if (!string.IsNullOrWhiteSpace(currentLoginUser.UserAccountInfo.UserLogoFilePath))
            {
                imgLogo.ImageUrl = Path.Combine(GlobalSettings.UserLogoFolder, Path.GetFileName(currentLoginUser.UserAccountInfo.UserLogoFilePath));
            }
            else
            {
                imgLogo.ImageUrl = GlobalSettings.DefaultLogoPhoto;
            }
        }

        private void DisplayProfilePhoto(CurrentLoginUser currentLoginUser)
        {
            if (currentLoginUser == null)
            {
                return;
            }

            if (!string.IsNullOrWhiteSpace(currentLoginUser.UserAccountInfo.UserProfilePhotoPath))
            {
                imgProfile.ImageUrl = Path.Combine(GlobalSettings.UserProfilePhotoFolder, Path.GetFileName(currentLoginUser.UserAccountInfo.UserProfilePhotoPath));
            }
            else
            {
                imgProfile.ImageUrl = GlobalSettings.DefaultProfilePhoto;
            }
        }

        protected void ProfileUploader_UploadedComplete(object sender, AsyncFileUploadEventArgs e)
        {
            if (ProfileUploader.PostedFile == null)
            {
                return;
            }

            _userAccountService = IocContainer.GetInstance<IUserAccountService>();
            _uploadFileManager = IocContainer.GetInstance<IUploadFileManager>();

            int currentLoginUserId = _securityService.GetLoginUserId();
            string savePath = _userAccountService.GetProfilePhotoFilePath(currentLoginUserId, e.FileName);

            CurrentLoginUser currentLoginUser = _securityService.GetLoginUserDetails();

            // check the format and size before proceeding 
            UploadPhotoValidationError validationError;
            if (!_uploadFileManager.ValidateUploadFileForUserProfileAndLogo(e.FileName, Convert.ToInt32(e.FileSize), out validationError))
            {
                return;
            }

            try
            {
                // delete the current file if it exists
                if (!string.IsNullOrWhiteSpace(currentLoginUser.UserAccountInfo.UserProfilePhotoPath))
                {
                    _uploadFileManager.DeleteFile(currentLoginUser.UserAccountInfo.UserProfilePhotoPath);
                }
            }
            catch (Exception ex)
            {
                // ignore the error
                Log.Error(FoothillModule.View, "Fail to delete previous uploaded user profile photo, file path is: " + currentLoginUser.UserAccountInfo.UserProfilePhotoPath, ex);
                return;
            }

            try
            {
                // save the uploaded file
                ProfileUploader.SaveAs(savePath);
            }
            catch (Exception ex)
            {
                Log.Error(FoothillModule.View, "Fail to save uploaded user profile photo, file path is: " + savePath, ex);
                return;
            }
            
            // update the database 
            if (_userAccountService.UpdateProfilePhotoFilePath(currentLoginUserId, savePath))
            {
                // update the current session
                currentLoginUser.UserAccountInfo.UserProfilePhotoPath = savePath;
            }
        }

        protected void LogoUploader_UploadedComplete(object sender, AsyncFileUploadEventArgs e)
        {
            if (LogoUploader.PostedFile == null)
            {
                return;
            }

            _userAccountService = IocContainer.GetInstance<IUserAccountService>();
            _uploadFileManager = IocContainer.GetInstance<IUploadFileManager>();

            int currentLoginUserId = _securityService.GetLoginUserId();
            string savePath = _userAccountService.GetLogoFilePath(currentLoginUserId, e.FileName);

            CurrentLoginUser currentLoginUser = _securityService.GetLoginUserDetails();

            // check the format and size before proceeding 
            UploadPhotoValidationError validationError;
            if (!_uploadFileManager.ValidateUploadFileForUserProfileAndLogo(e.FileName, Convert.ToInt32(e.FileSize), out validationError))
            {
                return;
            }

            try
            {
                // delete the current file if it exists
                if (!string.IsNullOrWhiteSpace(currentLoginUser.UserAccountInfo.UserLogoFilePath))
                {
                    _uploadFileManager.DeleteFile(currentLoginUser.UserAccountInfo.UserLogoFilePath);
                }
            }
            catch (Exception ex)
            {
                // ignore the error
                Log.Error(FoothillModule.View, "Fail to delete previous uploaded user logo photo, file path is: " + currentLoginUser.UserAccountInfo.UserLogoFilePath, ex);
                return;
            }

            try
            {
                // save the uploaded file
                LogoUploader.SaveAs(savePath);
            }
            catch (Exception ex)
            {
                Log.Error(FoothillModule.View, "Fail to save uploaded user logo, file path is: " + savePath, ex);
                return;
            }

            // update database
            if (_userAccountService.UpdateLogoFilePath(currentLoginUserId, savePath))
            {
                // update the current session
                currentLoginUser.UserAccountInfo.UserLogoFilePath = savePath;
            }
        }

        protected void SaveProfile(object sender, EventArgs e)
        {
            IValidationService validationService = IocContainer.GetInstance<IValidationService>();
            
            UserAccountDto userAccountDto = new UserAccountDto
            {
                ContactPhone = txtPhone.Text.Truncate(50),
                ContactName = txtContactName.Text.Truncate(50),
                Intro = validationService.SanitizeHtml(tbxIntro.Text.Truncate(5000))
            };
            
            CurrentLoginUser currentLoginUser = _securityService.GetLoginUserDetails();
            _userAccountService = IocContainer.GetInstance<IUserAccountService>();
            if (_userAccountService.UpdateUserAccount(currentLoginUser.UserAccountInfo.UserAccountId, userAccountDto))
            {
                lblFeedback.Text = EditProfile_aspx.UpdateSucceeded;
                lblFeedback.CssClass = "change-succeed";

                txtContactName.Text = userAccountDto.ContactName;
                txtPhone.Text = userAccountDto.ContactPhone;
                tbxIntro.Text = userAccountDto.Intro;

                currentLoginUser.UserAccountInfo.ContactName = userAccountDto.ContactName;
                currentLoginUser.UserAccountInfo.ContactPhone = userAccountDto.ContactPhone;
                currentLoginUser.UserAccountInfo.Intro = userAccountDto.Intro;
            }
            else
            {
                lblFeedback.Text = EditProfile_aspx.UpdateFailed;
                lblFeedback.CssClass = "change-failed";
            }
        }
    }
}